﻿using HuaCheng.CommonClass;
using HuaCheng.Model;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace HuaCheng.DataAccess
{
    public class UcChannelsHelper
    {
        /// <summary>
        /// 保存二进制通道数据
        /// </summary>
        /// <param name="chlList">通道集合</param>
        /// <param name="path">序列化保存路径</param>
        public static void SerialziedChannel(List<ChannelList> chlList, string path)
        {
            IFormatter serializer = new BinaryFormatter();
            FileStream saveFile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            serializer.Serialize(saveFile, chlList);//序列化对象集合
            saveFile.Close();
            ////将创建文件流写在using中，可以自动释放流所占用的资源
            //using (FileStream saveFile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            //{
            //    string jsonChl = JsonHelper.Serialize(chlList);
            //    byte[] buffer = Encoding.UTF8.GetBytes(jsonChl);
            //    saveFile.Write(buffer, 0, buffer.Length);
            //}

        }
        /// <summary>
        /// 反序列化通道数据
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<ChannelList> DeserializedChannels(string path)
        {
            List<ChannelList> chls = new List<ChannelList>();
            if (System.IO.File.Exists(path))//如果序列化文件存在
            {
                IFormatter serializer = new BinaryFormatter();
                FileStream loadFile = new FileStream(path, FileMode.Open, FileAccess.Read);
                chls = serializer.Deserialize(loadFile) as List<ChannelList>;//反序列对象集合
                loadFile.Close();
                //using (FileStream loadFile = new FileStream(path, FileMode.Open, FileAccess.Read))
                //{
                //    byte[] data = new byte[50];
                //    StringBuilder res = new StringBuilder();
                //    while (true)
                //    {
                //        int remain = loadFile.Read(data, 0, data.Length);
                //        if (remain == 0)
                //        {
                //            break;

                //        }
                //        res.Append(Encoding.UTF8.GetString(data, 0, remain));
                //    }
                //    chls = JsonHelper.Deserialize<List<ChannelList>>(res.ToString());
                //}
            }
            return chls;
        }
    }
}
